""" 
PS2 摇杆读取方位
接线:
    VRX --> 34 : adc读取引脚
    VRY --> 35 : adc读取引脚
    SW --> 36 : 按键读取引脚
    VCC --> 5V
    GND --> GND
"""

from machine import Pin, ADC
import time

VRX_ADC_PIN = 34
VRY_ADC_PIN = 35
SW_ADC_PIN = 36

adc_x = None
adc_y = None
adc_sw = None


def init_setup():
    global VRX_ADC_PIN, VRY_ADC_PIN, SW_ADC_PIN
    global adc_x, adc_y, adc_sw

    adc_x = ADC(Pin(VRX_ADC_PIN))
    adc_x.atten(ADC.ATTN_11DB)

    adc_y = ADC(Pin(VRY_ADC_PIN))
    adc_y.atten(ADC.ATTN_11DB)

    adc_sw = ADC(Pin(SW_ADC_PIN))
    adc_sw.atten(ADC.ATTN_11DB)


def ratio_map(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


def read_direaction():
    global adc_x, adc_y, adc_sw
    x = round(ratio_map(adc_x.read(), 0, 4095, 0, 255))
    y = round(ratio_map(adc_y.read(), 0, 4095, 0, 255))
    sw = round(ratio_map(adc_sw.read(), 0, 4095, 0, 255))
    print(f"X:{x}, Y:{y}, SW:{sw}")


def loop():
    while True:
        read_direaction()
        time.sleep(0.2)


if __name__ == "__main__":
    init_setup()
    loop()
